<template>
  <div class="app-container">
    <!-- 顶部控制台 -->
    <div class="filter-container" style="text-align: left">
      <el-row :gutter="0" style="margin-top: 15px">
        <el-col :span="24">
          <el-select class="filter-item" style="width: 80px" v-model="form.searchTitleType" size="mini">
            <el-option v-for="item in pageData.searchTitleTypeList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
          <el-input class="filter-item" style="width: 160px" v-model="form.searchTitle" size="mini" placeholder="请输入搜索的题目标题"/>
          <el-select class="filter-item" style="width: 120px" v-model="form.searchArea" size="mini" @change="handlePageInit" filterable>
            <el-option v-for="item in pageData.searchAreaList" :key="item.index" :label="item.label" :value="item.value"/>
          </el-select>
          <el-select class="filter-item" style="width: 120px" v-model="form.searchPlat" size="mini" @change="handlePageInit">
            <el-option v-for="item in pageData.searchPlatList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
          <el-select class="filter-item" style="width: 120px" v-model="form.searchType" size="mini" @change="handlePageInit">
            <el-option v-for="item in pageData.searchTypeList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
          <el-select class="filter-item" style="width: 120px" v-model="form.searchSort" size="mini" @change="handlePageInit">
            <el-option v-for="item in pageData.searchSortList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
          <el-select class="filter-item" style="width: 120px" v-model="form.searchDifficulty" size="mini" @change="handlePageInit">
            <el-option v-for="item in pageData.searchDifficultyList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
          <el-select class="filter-item" style="width: 120px" v-model="form.searchStatus" size="mini" @change="handlePageInit">
            <el-option v-for="item in pageData.searchStatusList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
          <el-select class="filter-item" style="width: 120px" v-model="form.searchUseStatus" size="mini" @change="handlePageInit">
            <el-option v-for="item in pageData.searchUseStatusList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
          <el-select class="filter-item" style="width: 120px" v-model="form.searchWarehouse" size="mini" @change="handlePageInit">
            <el-option v-for="item in pageData.searchWarehouseList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-col>
      </el-row>
      <el-row :gutter="0" style="margin-top: 15px">
        <el-col :span="24">
          <el-date-picker class="filter-item" size="mini" v-model="form.searchDate" type="daterange" :unlink-panels="pageData.unlinkPanels"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          :picker-options="pageData.pickerOptions" @change="handlePageInit">
          </el-date-picker>
          <el-cascader class="filter-item" size="mini" placeholder="考点标签"
                       v-model="form.searchLabelList1"
                       :options="pageData.searchLabelList"
                       :props="{ multiple: true, checkStrictly: true }"
                       clearable filterable>
          </el-cascader>
        </el-col>
      </el-row>
      <el-row :gutter="0" style="margin-top: 15px">
        <el-col :span="24">
          <el-button type="primary" icon="el-icon-search" @click="handlePageInit" size="mini">搜索</el-button>
          <el-button type="primary" icon="el-icon-search" @click="handleBatchReleaseData" size="mini">批量发布</el-button>
          <el-button type="danger" icon="el-icon-search" @click="handleBatchDeleteData" size="mini">批量下架</el-button>
          <el-button type="primary" icon="el-icon-search" @click="handleOpenSavePage" size="mini">新建题目</el-button>
          <el-button type="primary" icon="el-icon-search" @click="handleExportWordQuestion" size="mini">Word导出</el-button>
          <el-button type="primary" icon="el-icon-search" @click="handleExportExcelQuestion" size="mini">Excel导出</el-button>
          <el-button type="danger" icon="el-icon-search" @click="handleOpenCopyPanel" size="mini">批量迁移题库</el-button>
          <el-upload style="margin-top: 10px" ref="input" action="/" :show-file-list="false" :auto-upload="false" type="file" :on-change="handleImportQuestion">
            <el-button type="primary" icon="el-icon-search" size="mini">Excel导入</el-button>
          </el-upload>
        </el-col>
      </el-row>
    </div>
    <!-- 页面数据列表 -->
    <el-table :data="responseData.tableList"
              border style="width: 100%;"
              v-loading="pageData.loading"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.8)"
              :header-cell-style="{ background: '#545C64', color: '#ffffff' }"
              @selection-change="handleTableSelection">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column fixed="left" prop="examQuestionId" label="题目ID" width="270" align="center"/>
      <el-table-column prop="examQuestionName" label="题目" width="320" align="center"/>
      <el-table-column prop="examQuestionType" label="题型" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.examQuestionType === 1"><el-tag type="success">单选</el-tag></span>
          <span v-if="scope.row.examQuestionType === 2"><el-tag type="primary">多选</el-tag></span>
          <span v-if="scope.row.examQuestionType === 3"><el-tag type="warning">判断</el-tag></span>
          <span v-if="scope.row.examQuestionType === 4"><el-tag type="info">填空</el-tag></span>
          <span v-if="scope.row.examQuestionType === 5"><el-tag type="danger">简答</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column prop="examQuestionDifficultyType" label="难易度" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.examQuestionDifficultyType === 1"><el-tag type="success">简单</el-tag></span>
          <span v-if="scope.row.examQuestionDifficultyType === 2"><el-tag type="primary">中等</el-tag></span>
          <span v-if="scope.row.examQuestionDifficultyType === 3"><el-tag type="warning">困难</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column prop="examQuestionWarehouse" label="所属题库" align="center" width="320">
        <template slot-scope="scope">
          <span>
            <el-tag v-if="null != scope.row.examQuestionWarehouse || scope.row.examQuestionWarehouse === ''" type="primary">{{scope.row.examQuestionWarehouse}}</el-tag>
            <el-tag v-else type="warning">无库</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="examQuestionLabel" label="标签" width="320" align="center">
        <template slot-scope="scope">
            <span v-for="item in scope.row.examQuestionLabel.split(',')">
              <span v-if="item !== ''"><el-tag type="success">{{item}}</el-tag></span>
            </span>
        </template>
      </el-table-column>
      <el-table-column prop="examQuestionCreateTime" label="添加时间" width="180" align="center"/>
      <el-table-column prop="examQuestionPlatform" label="适用平台" width="280" align="center">
        <template slot-scope="scope">
            <span v-for="item in scope.row.examQuestionPlatform.split(',')">
              <span v-if="item !== '' && item === 1"><el-tag type="success">PC</el-tag></span>
              <span v-if="item !== '' && item === 2"><el-tag type="warning">APP</el-tag></span>
              <span v-if="item !== '' && item === 3"><el-tag type="primary">小程序</el-tag></span>
              <span v-if="item !== '' && item === 4"><el-tag type="info">视频锚点</el-tag></span>
            </span>
        </template>
      </el-table-column>
      <el-table-column prop="examQuestionStatus" label="审核状态" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.examQuestionStatus === 1"><el-tag type="success">已审核</el-tag></span>
          <span v-if="scope.row.examQuestionStatus === 0"><el-tag type="danger">未审核</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column prop="isUse" label="随堂小考" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.examQuestionUseStatus === 0"><el-tag type="danger">未引用</el-tag></span>
          <span v-else><el-tag type="success">已引用</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column prop="examQuestionCreateUser" label="出题人" width="120" align="center"/>
      <el-table-column fixed="right" label="操作" width="240" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleOpenEditPage(scope)">编辑</el-button>
          <el-button size="mini" type="success" v-if="scope.row.examQuestionStatus === 0" @click="handleUpdateDataStatus(scope, 1)">发布</el-button>
          <el-button size="mini" type="info" v-if="scope.row.examQuestionStatus === 1" @click="handleUpdateDataStatus(scope, 0)">下架</el-button>
          <el-button size="mini" type="danger" @click="handleDeleteData(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="form.pageNum"
      :page-size="form.pageSize"
      :total="form.total"
      :page-sizes="[12, 50, 100, 200]"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange">
    </el-pagination>
    <!-- 题库迁移面板 -->
    <el-dialog title="题库迁移" :visible.sync="pageData.copyPanelStatus" size="tiny" width="80%"
               :before-close="handleCloseCopyPanel">
      <el-card :body-style="{ padding: '0px' }">
        <el-select v-model="form.copyQuestion.questionWarehouseId"
                   filterable remote reserve-keyword
                   placeholder="请选择推荐文章"
                   :remote-method="handleRemoteQuestionWarehouseData">
          <el-option
            v-for="item in responseData.remoteSearchList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.type }}</span>
          </el-option>
        </el-select>
      </el-card>
      <el-button type="primary" size="small" @click="handleSaveCopyDataButtonClick">确定复制</el-button>
    </el-dialog>
  </div>
</template>

<script>
  // 组件引入
  import XLSX from "xlsx";
  import docxtemplater from 'docxtemplater';
  import PizZip from 'pizzip';
  import JSZipUtils from 'jszip-utils';
  import {saveAs} from 'file-saver';
  // 方法工具引入
  import { PermissionsToDetectFormUser } from '@/utils/PermissionsDetect';
  import { getPermission } from '@/utils/UserCookies';
  // 接口引入
  import { loadCmsChinaList,loadCmsExamQuestionList,loadCmsExportWordQuestionList,loadCmsExportExcelQuestionList,saveCmsImportExcelQuestionList,loadCmsExamLabelList,
    batchReleaseCmsExamQuestionData,loadCmsExamQuestionWarehouseLabelList,saveCmsExamQuestionCopyData } from "@/api/study";
  export default {
    name: "question",
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
      return {
        pageData:{
          searchTitleTypeList: [
            {label: "题目", value: 1},
            {label: "出题人", value: 2},
            {label: "题目ID", value: 3},
          ],// 标题类型筛选项
          searchAreaList: [
            {label: "请选择所属地域", value: -1}
          ],// 所属地域
          searchPlatList: [
            {label: "全部平台", value: -1},
            {label: "易考通PC", value: 1},
            {label: "易采通App", value: 2},
            {label: "小程序Applet", value: 3},
            {label: "视频锚点", value: 4},
          ],// 所属平台
          searchTypeList: [
            {label: "全部题型", value: -1},
            {label: "单选题", value: 1},
            {label: "多选题", value: 2},
            {label: "判断题", value: 3},
            {label: "填空题", value: 4},
            {label: "简答题", value: 5},
          ],// 题型筛选
          searchSortList: [
            {label: "默认排序", value: -1},
            {label: "标题排序", value: 1}
          ],// 排序分类
          searchDifficultyList: [
            {label: "难易度", value: -1},
            {label: "简单", value: 1},
            {label: "中等", value: 2},
            {label: "困难", value: 3}
          ],// 难易度
          searchStatusList: [
            {label: "发布状态", value: -2},
            {label: "未审核", value: -1},
            {label: "发布", value: 1},
            {label: "未发布", value: 0}
          ],// 发布状态
          searchUseStatusList: [
            {label: "使用状态", value: -1},
            {label: '已使用', value: 1},
            {label: '未引用', value: 0}
          ],// 引用状态
          searchWarehouseList: [
            {label: "所属题库", value: -1},
            {label: "无题库", value: 0},
          ],// 所属题库
          unlinkPanels: true,// 时间筛选
          pickerOptions: {
            shortcuts: [{
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }]
          },// 时间筛选
          searchLabelList: [{
            dictionaryId: '',
            dictionaryName: '',
            dictionaryDataList: [{
              dictionaryId: '',
              dictionaryName: ''
            }]
          }],// 标签筛选
          loading: false,
          copyPanelStatus: false,// 题库迁移
        },// 页面配置数据
        form:{
          searchTitleType: 1,// 标题类型筛选项
          searchTitle: "",// 筛选标题
          searchArea: -1,// 所属地域
          searchPlat: -1,// 所属平台
          searchType: -1,// 题型筛选
          searchSort: -1,// 排序分类
          searchDifficulty: -1,// 难易度
          searchStatus: -2,// 发布状态
          searchUseStatus: -1,// 引用状态
          searchWarehouse: -1,// 所属题库
          searchDate: "",// 创建时间
          startDate: "",
          endDate: "",
          searchLabelList1: [],// 标签筛选
          searchLabel: "",
          pageNum: 1,// 表单--页码
          pageSize: 12,// 表单--页面
          total: 0,// 表单--总量
          selection: [],// 多选的内容
          copyQuestion: {questionWarehouseId: ""}, // 题库复制
        },// 页面表单
        formRules: {},// 表单验证
        responseData: {
          tableList: [],
          chinaList: [],
          remoteSearchList: []
        },// 接口响应数据
      }
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods:{
      // 方法函数
      handlePageInit(){
        this.form.pageNum = 1;
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsExamQuestionList();
      },// 页面初始化事件
      handleCurrentChange(val){
        this.form.pageNum = val;// 更换页码
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsExamQuestionList();
      },// 页码切换事件
      handleSizeChange(val){
        this.form.pageSize = val;// 更换页面大小
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsExamQuestionList();
      },// 页面size切换事件
      handleTableSelection(val){
        let list = [];// 初始化多选数组
        for (let i=0; i<val.length; i++){
          list.push(val[i].examQuestionId);
        }// 遍历多选的列表，将ID拼入数组中
        this.form.selection = list;// 进行多选值的切换
      },// 表格多选事件
      handleBatchReleaseData(){
        if (PermissionsToDetectFormUser(getPermission(), "610005")){
          this.$confirm("是否发布当前所选数据?", "提示", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let param = {
              questionId: this.form.selection.toString(),
              questionStatus: 1
            };
            this.batchReleaseCmsExamQuestionData(param);
          }).catch(close => {
            console.log(close);
            this.$message.info("已取消操作");
          });
        } else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 批量发布按钮点击事件
      handleBatchDeleteData(){
        if (PermissionsToDetectFormUser(getPermission(), "610005")){
          this.$confirm("是否下架当前所选数据?", "提示", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let param = {
              questionId: this.form.selection.toString(),
              questionStatus: 0
            };
            this.batchReleaseCmsExamQuestionData(param);
          }).catch(close => {
            console.log(close);
            this.$message.info("已取消操作");
          });
        } else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 批量发布按钮点击事件
      handleOpenSavePage(){
        if (PermissionsToDetectFormUser(getPermission(), "610001")){
          this.$jump.push({path: "/study/questionSave"});
        }  else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 打开题目新增页面
      handleExportWordQuestion(){
        this.pageData.loading = true;
        this.loadCmsExportWordQuestionList();
      },// 导出word
      handleExportExcelQuestion(){
        this.pageData.loading = true;
        this.loadCmsExportExcelQuestionList();
      },// 导出excel
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },// 导出excel格式化JSON数据
      handleImportQuestion(file){
        this.pageData.loading = true;
        const types = file.name.split(".")[1];
        const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt"].some(item => item === types);
        if (!fileType) {
          this.$message.warning("格式错误！请重新选择");
          return;
        }
        this.file2Xce(file).then(tabJson => {
          let list = tabJson[0].sheet;
          if (list.length > 0){
            let merchantList = this.dateTransition(list);
            let data = {list: merchantList};
            this.saveCmsImportExcelQuestionList(data);
          }
        });
      },// 导入excel
      dateTransition(data){
        let list = [];
        let obj = {};
        let outData =data;
        for(var i = 0; i <outData.length; i++) {
          obj = {};
          for(var key in outData[i]) {
            if(key == '题目') {
              obj['examQuestionName'] = outData[i][key];
            } else if(key == '商家名称') {
              obj['name'] = outData[i][key];
            } else if(key == '选项') {
              obj['examQuestionOption'] = outData[i][key];
            } else if(key == '正确答案') {
              obj['examQuestionCorrectAnswer'] = outData[i][key];
            } else if(key == '题型') {
              obj['examQuestionType'] = outData[i][key];
            } else if(key == '难易度') {
              obj['examQuestionDifficultyType'] = outData[i][key];
            } else if(key == '所属题库') {
              obj['examQuestionWarehouse'] = outData[i][key];
            } else if(key == '地域') {
              obj['examQuestionTerritoryType'] = outData[i][key];
            } else if(key == '审核状态') {
              obj['examQuestionStatus'] = outData[i][key];
            } else if(key == '出题人') {
              obj['examQuestionCreateUser'] = outData[i][key];
            } else if(key == '考试重点') {
              obj['examPoint'] = outData[i][key];
            } else if(key == '热门关键词') {
              obj['examKeyword'] = outData[i][key];
            } else if(key == '项目类别') {
              obj['examProject'] = outData[i][key];
            } else if(key == '热门行业') {
              obj['examIndustry'] = outData[i][key];
            } else if(key == '采购当事人') {
              obj['examPurchaser'] = outData[i][key];
            } else if(key == '采购方式') {
              obj['examProcurementMethod'] = outData[i][key];
            } else if(key == '法律法规') {
              obj['examLaw'] = outData[i][key];
            } else if (key == '答案解析') {
              obj['examQuestionInfo'] = outData[i][key];
            }
          }
          list.push(obj);
        }
        return list;
      },// 导入excel格式化数据
      file2Xce(file) {
        return new Promise(function(resolve, reject) {
          const reader = new FileReader();
          reader.onload = function(e) {
            const data = e.target.result;
            this.wb = XLSX.read(data, {
              type: "binary"
            });
            const result = [];
            this.wb.SheetNames.forEach(sheetName => {
              result.push({
                sheetName: sheetName,
                sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
              });
            });
            resolve(result);
          };
          reader.readAsBinaryString(file.raw);
        });
      },// 导入excel格式化数据
      handleOpenCopyPanel(){
        this.pageData.copyPanelStatus = true;
      },// 打开题目一键迁移面板
      handleCloseCopyPanel(){
        this.$confirm("确认关闭？").then(response => {
          // 打开面板
          this.pageData.copyPanelStatus = false;
          this.form.copyQuestion.questionWarehouseId = "";
        }).catch(err => {
          console.log(err);
        });
      },// 关闭题目一键迁移面板
      handleRemoteQuestionWarehouseData(query){
        if (this.form.selection.length == 0){
          this.$message.warning("请先选择题目数据");
          return;
        }
        if (query !== "") {
          let param = {
            searchTitle: query,
          };
          this.loadCmsExamQuestionWarehouseLabelList2(param);
        } else {
          this.responseData.remoteSearchList = [];
        }
      },// 远程搜索可用题库列表
      handleSaveCopyDataButtonClick(){
        this.$confirm('当前操作会将所选题目数据完全复制到当前题库内, 请核对后继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = {
            questionList: this.form.selection,
            examQuestionWarehouseId: this.form.copyQuestion.questionWarehouseId
          };
          this.saveCmsExamQuestionCopyData(param);
        }).catch(close => {
          console.log(close);
          this.$message.info("已取消操作");
        });
      },// 保存复制面板数据
      handleOpenEditPage(scope){
        if (PermissionsToDetectFormUser(getPermission(), "610003")){
          let routeUrl = this.$router.resolve({
            path: "/study/questionEdit",
            query: {questionId: scope.row.examQuestionId}
          });
          window.open(routeUrl.href, '_blank');
          // _this.$jump.push({path: '/QuestionBankEdit', query: {questionId: scope.row.examQuestionId}});
        }  else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 打开题目修改页
      handleUpdateDataStatus(scope, status){
        if (PermissionsToDetectFormUser(getPermission(), "610005")){
          if (scope.row.examQuestionUseStatus != 0){
            this.$confirm("本题为随堂小考，是否确认下架?", "提示", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let param = {
                questionId: scope.row.examQuestionId,
                questionStatus: status
              };
              this.batchReleaseCmsExamQuestionData(param);
            }).catch(close => {
              console.log(close);
              this.$message.info("已取消操作");
            });
          } else {
            this.$confirm("是否更改当前所选数据的发布状态?", "提示", {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let param = {
                questionId: scope.row.examQuestionId,
                questionStatus: status
              };
              this.batchReleaseCmsExamQuestionData(param);
            }).catch(close => {
              console.log(close);
              this.$message.info("已取消操作");
            });
          }
        } else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 更改内容发布状态
      handleDeleteData(scope){
        this.$message.info("该功能暂未开放，如有需要请联系管理员");
      },// 删除数据按钮
      // 接口
      loadCmsChinaList(){
        loadCmsChinaList().then(response => {
          if (response.code === "200"){
            this.pageData.searchAreaList = this.pageData.searchAreaList.concat(response.data);
          } else {
            console.log(response.message);
            this.$message.warning(response.message);
          }
        }).catch(error =>{
          console.log(error);
          this.$message.error(error);
        });
      },// 获取地区字典列表
      loadCmsExamLabelList(){
        loadCmsExamLabelList().then(response => {
          if (response.code === "200"){
            this.pageData.searchLabelList = response.data;
            this.pageData.loading = false;
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 获取考点标签数据
      loadCmsExamQuestionWarehouseLabelList(){
        loadCmsExamQuestionWarehouseLabelList().then(response => {
          if (response.code === "200"){
            this.pageData.searchWarehouseList = this.pageData.searchWarehouseList.concat(response.data);
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 获取题库列表数据
      loadCmsExamQuestionWarehouseLabelList2(param){
        loadCmsExamQuestionWarehouseLabelList(param).then(response => {
          if (response.code === "200"){
            this.responseData.remoteSearchList = response.data;
          } else {
            this.$message.warning(response.message);
            this.responseData.remoteSearchList = [];
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 获取题库筛选项
      loadCmsExamQuestionList(){
        // 时间字段处理
        if (this.form.searchDate !== "" && this.form.searchDate !== "0" && this.form.searchDate != null){
          let date1 = new Date(this.form.searchDate[0]);
          this.form.startDate = date1.getFullYear()+"-"+("0"+(date1.getMonth()+1)).slice(-2)+"-"+date1.getDate() + " 00:00:00";
          let date2 = new Date(this.form.searchDate[1]);
          this.form.endDate = date2.getFullYear()+"-"+("0"+(date2.getMonth()+1)).slice(-2)+"-"+date2.getDate() + " 23:59:59";
        }
        // 考点标签处理
        if (this.form.searchLabelList1.length > 0){
          // 格式化考题标签信息
          let array = [];
          for (let i=0;i<this.form.searchLabelList1.length;i++){
            for (let j=0;j<this.form.searchLabelList1[i].length;j++){
              array.push(this.form.searchLabelList1[i][j]);
            }
          }
          // 数组去重
          array = array.filter(function(item,index){
            return array.indexOf(item,0) === index;
          });
          let array2 = [];
          for (let i=0;i<array.length;i++){
            let result = 2;
            let index = 0;
            for (let j=0;j<array2.length;j++){
              let str1 = array[i];
              let str2 = array2[j];
              if (str1.toString().substr(0,1) == str2.toString().substr(0,1)) {// 首字符相等，代表有相同系列
                if (array[i] != array2[j]) {// 两个值不相等，可以进行添加
                  if (array[i].toString().length > array2[j].toString().length){// 如果新数据长度更长，则需要进行替换
                    result = 1;
                    index = j;
                  } else {
                    result = 2;
                  }
                } else {
                  result = 0;
                }
              } else {
                // 没有相同值，添加新值
                result = 2;
              }
            }
            if (result === 1){
              array2[index] = array[i];
            } else if (result === 2){
              array2.push(array[i]);
            }
          }
          this.form.searchLabel = array2.toString();
        } else {
          this.form.searchLabel = "";
        }
        loadCmsExamQuestionList(this.form).then(response => {
          if (response.code === "200"){
            this.pageData.loading = false;
            this.responseData.tableList = response.data.list;
            this.form.total = response.data.total;
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 获取题库列表
      loadCmsExportWordQuestionList(){
        if (this.form.searchDate !== "" && this.form.searchDate !== "0" && this.form.searchDate != null){
          let date1 = new Date(this.form.searchDate[0]);
          this.form.startDate = date1.getFullYear()+"-"+("0"+(date1.getMonth()+1)).slice(-2)+"-"+date1.getDate() + " 00:00:00";
          let date2 = new Date(this.form.searchDate[1]);
          this.form.endDate = date2.getFullYear()+"-"+("0"+(date2.getMonth()+1)).slice(-2)+"-"+date2.getDate() + " 23:59:59";
        }
        loadCmsExportWordQuestionList(this.form).then(response => {
          if (response.code === "200"){
            this.pageData.loading = false;
            // 读取并获得模板文件的二进制内容
            JSZipUtils.getBinaryContent('/static/word/question_template.docx', function (error, content) {
              // question_template.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
              if (error){
                console.log(error);
                throw error;
              }
              // 创建一个PizZip实例，内容为模板内容
              let zip = new PizZip(content);
              // 创建并加载docxtemplater实例对象
              let doc = new docxtemplater().loadZip(zip);
              // 设置模板变量值
              doc.setData({
                table: response.data
              });
              try {
                // 用模板变量的值替换所有模板变量
                doc.render();
              } catch (e) {
                // 抛出异常
                let e = {
                  message: error.message,
                  name: error.name,
                  stack: error.stack,
                  properties: error.properties
                };
                console.log(JSON.stringify({ error: e }));
                throw error;
              }
              // 生成一个代表docxtemplater对象自拍文件(不是一个真实的文件，而是在内存中的表示)
              let out = doc.getZip().generate({
                type: 'blob',
                mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
              });
              // 将目标对象保存为目标类型的文件，并命名
              saveAs(out, "题库Word导出文档.docx");
            })
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        });
      },// 导出题库Word表
      loadCmsExportExcelQuestionList(){
        if (this.form.searchDate !== "" && this.form.searchDate !== "0" && this.form.searchDate != null){
          let date1 = new Date(this.form.searchDate[0]);
          this.form.startDate = date1.getFullYear()+"-"+("0"+(date1.getMonth()+1)).slice(-2)+"-"+date1.getDate() + " 00:00:00";
          let date2 = new Date(this.form.searchDate[1]);
          this.form.endDate = date2.getFullYear()+"-"+("0"+(date2.getMonth()+1)).slice(-2)+"-"+date2.getDate() + " 23:59:59";
        }
        loadCmsExportExcelQuestionList(this.form).then(response => {
          if (response.code === "200"){
            this.pageData.loading = false;
            // 执行生成表格操作
            require.ensure([], () => {
              const { export_json_to_excel } = require('@/Excel/Export2Excel');//注意这个Export2Excel路径
              const tHeader = [
                '题目','选项','正确答案','题型','难易度','所属题库','地域','审核状态','出题人','考试重点','热门关键词','项目类别','热门行业','采购当事人','采购方式','法律法规','答案解析'
              ];   // 上面设置Excel的表格第一行的标题
              const filterVal = [
                'examQuestionName','examQuestionOption','examQuestionCorrectAnswer','examQuestionType','examQuestionDifficultyType','examQuestionWarehouse',
                'examQuestionTerritoryType','examQuestionStatus','examQuestionCreateUser','examPoint','examKeyword','examProject','examIndustry',
                'examPurchaser','examProcurementMethod','examLaw','examQuestionInfo'
              ]; // 上面的index、nickName、name是tableData里对象的属性key值
              const list = response.data;  //把要导出的数据tableData存到list
              const data = this.formatJson(filterVal, list);
              export_json_to_excel(tHeader, data, '题库Excel导出文档');//最后一个是表名字
            });
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        });
      },// 导出题库Excel表
      saveCmsImportExcelQuestionList(param){
        saveCmsImportExcelQuestionList(param).then(response => {
          if (response.code === '200'){
            this.pageData.loading = false;
            this.$message.success("数据导入成功");
            this.handlePageInit();
          } else {
            this.pageData.loading = false;
            this.$message.warning(response.message);
            // 执行生成表格操作
            require.ensure([], () => {
              const { export_json_to_excel } = require('@/Excel/Export2Excel');//注意这个Export2Excel路径
              const tHeader = [
                '题目','选项','正确答案','题型','难易度','所属题库','地域','审核状态','出题人','考试重点','热门关键词','项目类别','热门行业','采购当事人','采购方式','法律法规','答案解析'
              ];   // 上面设置Excel的表格第一行的标题
              const filterVal = [
                'examQuestionName','examQuestionOption','examQuestionCorrectAnswer','examQuestionType','examQuestionDifficultyType','examQuestionWarehouse',
                'examQuestionTerritoryType','examQuestionStatus','examQuestionCreateUser','examPoint','examKeyword','examProject','examIndustry',
                'examPurchaser','examProcurementMethod','examLaw', 'examQuestionInfo'
              ]; // 上面的index、nickName、name是tableData里对象的属性key值
              const list = response.data;  //把要导出的数据tableData存到list
              const data = this.formatJson(filterVal, list);
              export_json_to_excel(tHeader, data, '题库Excel导入异常文档');//最后一个是表名字
            });
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        });
      },// 导入Excel表
      batchReleaseCmsExamQuestionData(param){
        batchReleaseCmsExamQuestionData(param).then(response => {
          if (response.code === '200'){
            this.$message.success('数据状态更新成功');
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        })
      },// 更新数据发布状态
      saveCmsExamQuestionCopyData(param){
        saveCmsExamQuestionCopyData(param).then(response => {
          if (response.code === '200'){
            this.$message.success("题目复制成功");
            this.pageData.copyPanelStatus = false;
            this.form.copyQuestion.questionWarehouseId = "";
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        });
      },// 保存题目复制数据
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created: function () {
      let _this = this;
      // 进行初始化数据读取
      this.loadCmsExamLabelList();
      this.loadCmsExamQuestionWarehouseLabelList();
      this.loadCmsChinaList();
      // 先获取缓存中是否有题库参数
      if (localStorage.getItem("searchWarehouse")) {
        this.form.searchWarehouse = localStorage.getItem("searchWarehouse");
        localStorage.removeItem("searchWarehouse");
      }
      setTimeout(function () {
        document.onkeydown = function(e) {
          if (!_this.pageData.loading) {
            let key = window.event.keyCode;
            if (key === 13) {
              _this.handlePageInit(); //此方法是当按下enter键后要做的动作。
            }
          }
        };
        _this.handlePageInit();
      }, 800);
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
